<template>

  <div class="app-container" v-if="canList">
    <div class="filter-container">

      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                placeholder="转账人编号"
                v-model="listQuery.entity.fromUser.code">
      </el-input>

      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                placeholder="到账人编号"
                v-model="listQuery.entity.toUser.code">
      </el-input>

      <!--            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"-->
      <!--                      placeholder="到账人名字"-->
      <!--                      v-model="listQuery.entity.toUser.name">-->
      <!--            </el-input>-->

      <el-select @change='handleFilter' clearable class="filter-item input" style="width: 130px"
                 v-model="listQuery.entity.record.type"
                 placeholder="类型">
        <el-option v-for="(item,index) in  typeOptions" :key="item" :label="item" :value="index">
        </el-option>
      </el-select>

      <el-select @change='handleFilter' clearable class="filter-item input" style="width: 130px"
                 v-model="listQuery.entity.record.bus"
                 placeholder="业务">
        <el-option v-for="(item,index) in  busOptions" :key="item" :label="item" :value="index">
        </el-option>
      </el-select>

      <el-select @change='handleFilter' clearable class="filter-item input" style="width: 130px"
                 v-model="listQuery.entity.record.statusOptions"
                 placeholder="状态">
        <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item" :value="index">
        </el-option>
      </el-select>


      <!--            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"-->
      <!--                      placeholder="变动原因"-->
      <!--                      v-model="listQuery.info">-->
      <!--            </el-input>-->
      <el-date-picker
          value-format="yyyy-MM-dd HH:mm:ss"
          class="filter-item input"
          v-model="listQuery.entity.record.times"
          type="datetimerange"
          range-separator="至"
          start-placeholder="变动时间开始日期"
          end-placeholder="变动时间结束日期">
      </el-date-picker>

      <div style="display: inline-block">
        <el-button class="filter-item" type="primary" v-waves icon="el-icon-search"
                   @click="handleFilter">查找
        </el-button>
        <!--                <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary"-->
        <!--                           v-if="canSave" icon="el-icon-edit">添加-->
        <!--                </el-button>-->
        <!--                <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"-->
        <!--                           @click="handleDownload">导出-->
        <!--                </el-button>-->
      </div>


    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row
              style="width: 100%;margin-bottom: 24px">
      <!--            <el-table-column align="center" label="序号">-->
      <!--                <template slot-scope="scope">-->
      <!--                    <span>{{scope.$index}}</span>-->
      <!--                </template>-->
      <!--            </el-table-column>-->
      <el-table-column align="center" label="转账人">
        <template slot-scope="scope">
          <span>{{scope.row.fromUser.name}}-{{scope.row.fromUser.code}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="到账人">
        <template slot-scope="scope">
          <span>{{scope.row.toUser.name}}-{{scope.row.toUser.code}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型">
        <template slot-scope="scope">
                   <span>

                         <el-tag :type="tagTypes[scope.row.type]">     {{typeOptions[scope.row.record.type]}}</el-tag>

                        </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="变动数量">
        <template slot-scope="scope">
          <span>{{scope.row.record.amount}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="转账人剩余">
        <template slot-scope="scope">
          <span>{{scope.row.record.fromNowAmount}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="到账人剩余">
        <template slot-scope="scope">
          <span>{{scope.row.record.toNowAmount}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="事由">
        <template slot-scope="scope">
          <span>{{scope.row.record.info}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="变动时间">
        <template slot-scope="scope">
          <span>{{parseTime(scope.row.record.time)}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="业务">
        <template slot-scope="scope">
                   <span>

                         <el-tag :type="tagTypes[scope.row.bus]">     {{busOptions[scope.row.record.bus]}}</el-tag>

                        </span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
                   <span>

                         <el-tag :type="tagTypes[scope.row.status]">     {{statusOptions[scope.row.record.status]}}</el-tag>

                        </span>
        </template>
      </el-table-column>

      <!--            <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">-->
      <!--                <template slot-scope="scope">-->
      <!--                    <el-button type="primary" v-if="canUpdate" size="mini" @click="handleUpdate(scope.row)">编辑-->
      <!--                    </el-button>-->
      <!--                    <el-button v-if="canSave" size="mini" type="danger"-->
      <!--                               @click="handleDelete(scope.row)">删除-->
      <!--                    </el-button>-->
      <!--                </template>-->
      <!--            </el-table-column>-->

    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!--        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">-->
    <!--            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px"-->
    <!--                     style='width: 450px; margin-left:50px;'>-->
    <!--                <el-form-item label="转账人" prop="fromUserId">-->
    <!--                    <el-input v-model="temp.fromUserId"></el-input>-->
    <!--                </el-form-item>-->
    <!--                <el-form-item label="到账人" prop="toUserId">-->
    <!--                    <el-input v-model="temp.toUserId"></el-input>-->
    <!--                </el-form-item>-->
    <!--                <el-form-item label="账户类型" prop="type">-->
    <!--                    <el-input v-model="temp.type"></el-input>-->
    <!--                </el-form-item>-->
    <!--                <el-form-item label="变动数量" prop="amount">-->
    <!--                    <el-input v-model="temp.amount"></el-input>-->
    <!--                </el-form-item>-->
    <!--                <el-form-item label="转账人剩余数量" prop="fromNowAmount">-->
    <!--                    <el-input v-model="temp.fromNowAmount"></el-input>-->
    <!--                </el-form-item>-->
    <!--                <el-form-item label="到账人剩余数量" prop="toNowAmount">-->
    <!--                    <el-input v-model="temp.toNowAmount"></el-input>-->
    <!--                </el-form-item>-->
    <!--                <el-form-item label="变动原因" prop="info">-->
    <!--                    <el-input v-model="temp.info"></el-input>-->
    <!--                </el-form-item>-->
    <!--                <el-form-item label="变动时间" prop="date">-->
    <!--                    <el-date-picker v-model="temp.time" type="datetime"-->
    <!--                                    value-format="yyyy-MM-dd HH:mm:ss" placeholder="变动时间">-->
    <!--                    </el-date-picker>-->
    <!--                </el-form-item>-->

    <!--            </el-form>-->
    <!--            <div slot="footer" class="dialog-footer">-->
    <!--                <el-button @click="closeDialogForm">取消</el-button>-->
    <!--                <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>-->
    <!--                <el-button v-else type="primary" @click="updateData">确认</el-button>-->
    <!--            </div>-->
    <!--        </el-dialog>-->
  </div>
</template>
<style type="stylus">
.filter-container {
  /*padding-bottom: 20px;*/
}

.filter-item {
  margin-bottom: 10px;
}

.filter-item.input {
  /*line-height: 60px*/
  margin-right: 10px;
}
</style>

<script>
import {list, save, update, remove} from '@/api/account_record'
import waves from '@/directive/waves' // 水波纹指令
import {parseTime} from '@/utils'


import {mapGetters} from 'vuex'
import {hasAuth} from '@/utils/auth'
import {MessageBox, Message} from 'element-ui'

export default {
  name: 'test',
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      time: null,
      typeOptions: ["代金券", "积分", "优惠券", "换购券", "经验值", "捐赠"],
      busOptions: ["调配", "充值", "货款", "分享奖励", "追回奖励", "支付", "自动支付", "区域奖励", "店铺利润", "店铺管理利润"],
      statusOptions: ["未完成", "已完成"],
      tagTypes: ['info', '', 'warning', 'danger', 'warning'],
      listQuery: {
        json: true,
        page: 1,
        limit: 20,
        order: 'record.id desc',
        entity: {
          record: {
            bus: null,
            fromUserId: null,
            hide: false,
            toUserId: null
            ,
            type: null
            ,
            amount: null
            ,
            fromNowAmount: null
            ,
            toNowAmount: null
            ,
            info: null
            ,
            time: null,
            times: null
          },
          fromUser: {
            name: null,
            id: null
          },
          toUser: {
            name: null,
            id: null
          }
        }

      },
      temp:
          {
            id: null,
            fromUserId: null,
            toUserId: null,
            type: null,
            amount: null,
            fromNowAmount: null,
            toNowAmount: null,
            time: null,
            info: null
          }
      ,
      dialogFormVisible: false,
      dialogStatus:
          '',
      textMap:
          {
            update: '修改',
            create:
                '新增'
          }
      ,
      rules:
          {
            fromUserId: [
              {
                required: false, message:
                    '必填字段', trigger:
                    'change'
              }
            ]
            ,
            toUserId: [
              {
                required: false, message:
                    '必填字段', trigger:
                    'change'
              }
            ]
            ,
            type: [
              {
                required: false, message:
                    '必填字段', trigger:
                    'change'
              }
            ]
            ,
            amount: [
              {
                required: false, message:
                    '必填字段', trigger:
                    'change'
              }
            ]
            ,
            fromNowAmount: [
              {
                required: false, message:
                    '必填字段', trigger:
                    'change'
              }
            ]
            ,
            toNowAmount: [
              {
                required: false, message:
                    '必填字段', trigger:
                    'change'
              }
            ]
            ,
            time: [
              {
                required: false, message:
                    '必填字段', trigger:
                    'change'
              }
            ]
            ,
            info: [
              {
                required: false, message:
                    '必填字段', trigger:
                    'change'
              }
            ]
          }
      ,
      downloadLoading: false,
      qData:
          {
            token: '',
            key:
                ''
          }
    }
  },
  created() {
    this.getList()
  },
  computed: {
    ...mapGetters([
      'perms'
    ]),
    canSave() {
      return hasAuth(this.perms, 'account:record:save')
    },
    canDelete() {
      return hasAuth(this.perms, 'account:record:delete')
    },
    canUpdate() {
      return hasAuth(this.perms, 'account:record:update')
    },
    canList() {
      return hasAuth(this.perms, 'account:record:list')
    }
  },
  methods: {
    parseTime(time) {
      return parseTime(time, '{y}-{m}-{d}')
    },
    getList() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      Message({
        message: '旧数据异常' || 'error',
        type: 'error',
        duration: 5 * 1000
      })
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    beforeFormShow(row) {
      this.resetTemp(row) // 更新数据
      // 存在图片

    },
    afterFormShow(row) {

    },
    beforeFormCommit() {
    },
    resetTemp(row) {

      this.temp = {}
      if (row) {
        this.temp = Object.assign({}, row) // copy obj
      }

    },
    handleCreate() {
      this.beforeFormShow()
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.afterFormShow()
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      // this.beforeFormShow(row)
      // this.temp = Object.assign({}, row) // copy obj
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // })
        // console.log(row.record.id)
        this.deleteData([row.record.id])
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              this.beforeFormCommit()
              save(this.temp).then(res => {
                this.temp = res.data
                this.list.unshift(this.temp)
                this.closeDialogForm()
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
              })
            }
          }
      )
    },
    deleteData(ids) {
      // const ids = [this.temp.id]
      remove({ids}).then(res => {
        // 从当前队列中移除
        for (const v of this.list) {
          if (ids.indexOf(v.record.id) > -1) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1)
            break
          }
          // if (v.id === this.temp.id) {
          //     const index = this.list.indexOf(v)
          //     this.list.splice(index, 1)
          //     break
          // }
        }
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleUpdate(row) {
      this.beforeFormShow(row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              this.beforeFormCommit()
              update(this.temp).then(() => {
                for (const v of this.list
                    ) {
                  if (v.id === this.temp.id) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.temp)
                    break
                  }
                }
                this.closeDialogForm()
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                })
              })
            }
          }
      )
    },
    closeDialogForm() {
      this.dialogFormVisible = false
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '序号'
          ,
          '转账人'
          ,
          '到账人'
          ,
          '账户类型'
          ,
          '变动数量'
          ,
          '转账人剩余'
          ,
          '到账人剩余'
          ,
          '变动原因'
          ,
          '变动时间'
        ]
        const filterVal = ['id'
          , 'fromUserId'
          , 'toUserId'
          , 'type'
          , 'amount'
          , 'fromNowAmount'
          , 'toNowAmount'
          , 'info'
          ,
          'time'
        ]
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
            return v[j]
          }
      ))
    },
  }
}
</script>
